<?php

// 会员红包记录表

namespace app\console\controller;

use think\Db;
use think\Url;
use think\Loader;
use think\Request;
use think\Controller;
use app\common\excel\Export;
use app\console\model\Coupon as CouponModel;
use app\console\model\MemberCoupon as MemberCouponModel;

class MemberCoupon extends Controller
{


    public function index(Request $request, MemberCouponModel $memberCoupon)
    {
        // 获取参数
        $inquire = Request::instance()->param();
        $where = [];
       if(!empty($inquire['status'])) $where['mc.status'] = ['eq',$inquire['status']];
        if(!empty($inquire['coupon_id'])) $where['coupon_id'] = ['eq',$inquire['coupon_id']];
        if(!empty($inquire['type'])) $where['mc.type'] = ['eq',$inquire['type']];
        if(!empty($inquire['single_id'])) $where['mc.single_id'] = ['eq',$inquire['single_id']];
        if(!empty($inquire['title'])) $where['m.username|mc.title|mc.create_time'] = ['like','%'.$inquire['title'].'%'];
        if (!empty($inquire['interval_timer'])) {
            $interval_timer = explode(' / ', $inquire['interval_timer']);
            $where['mc.create_time'] = ['between time', [($interval_timer[0]), ($interval_timer[1])]];
        }
        // 搜索条件
      $data = (new MemberCouponModel())
          ->alias('mc')
          ->join('member m','mc.member_id = m.id','left')
          ->join('coupon c','mc.coupon_id = m.id','left')
          ->field('mc.*,m.username')
          ->where($where)
          ->order('id','desc')
          ->paginate(10,false,['query' => $inquire])->each(function($item,$key){
              if($item->type == 1){
                  $item->type = '商品优惠券';
              }
              if($item->type == 2){
                  $item->type = '服务优惠券';
              }
              $item->single_id = Db::name('single')->where('id',$item->single_id)->value('cat_name');
          });
        $single = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])->where('id','not in','11,5,6,7,9,10')->select();
        $single = getMenuTree($single);
        return $this->fetch('index', [
            'mate_title'    => '优惠券记录列表',
            'data' => $data,

            'single' => $single

        ]);
    }

    /*
     * 优惠券记录编辑
     */
    public function update($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('MemberCoupon');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = (new MemberCouponModel())->allowField(true)->save($data, ['id' => $id]);

            if ($dispose) {
                win('操作成功', Url::build('MemberCoupon/index'));
            }

            fail('操作失败');

        }

        // 读取数据
        $item = Db::view('member_coupon', 'id,member_id,title,minus_price,total_price,start_time,end_time,status,create_time,multi_pic')
            ->view('coupon','multi_pic multi_pic11','coupon.id = member_coupon.coupon_id')
            ->view('member', 'username', 'member_coupon.member_id = member.id')
            ->where(['id' => $id])
            ->find();

        return $this->fetch('create', [
            "mate_title" => '优惠券记录查看',
            'item'       => $item

        ]);
    }


    /*
    * 优惠券记录删除
    */
    public function destroy($id)
    {

        if (MemberCouponModel::destroy($id)) {
            win('操作成功', Url::build('MemberCoupon/index'));
        }

        fail('操作失败');

    }


    /*
    * 排列顺序
    */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            MemberCouponModel::where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('MemberCoupon/index'));
    }


    //导出
    public function export()
    {
        $inquire = Request::instance()->param();
        $where = [];
        if(!empty($inquire['status'])) $where['mc.status'] = ['eq',$inquire['status']];
        if(!empty($inquire['coupon_id'])) $where['coupon_id'] = ['eq',$inquire['coupon_id']];
        if(!empty($inquire['type'])) $where['mc.type'] = ['eq',$inquire['type']];
        if(!empty($inquire['single_id'])) $where['mc.single_id'] = ['eq',$inquire['single_id']];
        if(!empty($inquire['title'])) $where['m.username|mc.title|mc.create_time'] = ['like','%'.$inquire['title'].'%'];
        $data = (new MemberCouponModel())
            ->alias('mc')
            ->join('member m','mc.member_id = m.id','left')
            ->join('coupon c','mc.coupon_id = m.id','left')
            ->field('mc.*,m.username')
            ->where($where)
            ->order('id','desc')
            ->select()->toArray();
        if(!empty($data)){
            foreach ($data as $k => &$v){
                if($v['type'] == 1){
                    $v['type'] = '商品优惠券';
                }
                if($v['type'] == 2){
                    $v['type'] = '服务优惠券';
                }
                $v['single_id'] = Db::name('single')->where('id',$v['single_id'])->value('cat_name');
//                switch ($v['status']){
//                    case 1;
//                        $v['status'] = '未使用';
//                    break;
//                    case 2;
//                        $v['status'] = '已使用';
//                    break;
//                }
                if($v['status'] == 1) $v['status']= '未使用';
                if($v['status'] == 2) $v['status']= '已使用';
            }
        }

        $this->push_coupon($data,'优惠券记录导出');
    }

    public function push_coupon($data,$name = 'Excel')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '会员')
            ->setCellValue('B1', '优惠券类型')
            ->setCellValue('C1', '服务类型')
            ->setCellValue('D1', '优惠券标题')
            ->setCellValue('E1', '总金额')
            ->setCellValue('F1', '满减金额')
            ->setCellValue('G1', '开始时间')
            ->setCellValue('H1', '结束时间')
            ->setCellValue('I1', '使用状态')
            ->setCellValue('J1', '领取时间');
        $sheet1 = ['A', 'B', 'C', 'D', 'I'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, "\t".$v['username']."\t")
                ->setCellValue('B' . $num, $v['type'])
                ->setCellValue('C' . $num, $v['single_id'])
                ->setCellValue('D' . $num, $v['title'])
                ->setCellValue('E' . $num, $v['total_price'])
                ->setCellValue('F' . $num, $v['minus_price'])
                ->setCellValue('G' . $num, date('Y-m-d H:i:s',$v['start_time']))
                ->setCellValue('H' . $num, date('Y-m-d H:i:s',$v['end_time']))
                ->setCellValue('I' . $num, $v['status'])
                ->setCellValue('J' . $num, date('Y-m-d H:i:s',$v['create_time']));
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('优惠券记录导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }
}